package org.zhengquan.util;


import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

/**
 * @author zhengquan
 * @date 2017/10/27
 */
@Slf4j
public class JsonMapper {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }

    public static <T> String obj2Str(T t) {
        if (t == null) {
            return null;
        }
        try {
            return t instanceof String ? (String) t : objectMapper.writeValueAsString(t);
        } catch (Exception e) {
            log.warn("parse Object to String exception,errors:{}", e);
            return null;
        }
    }

    public static <T> T str2Obj(String str, TypeReference<T> reference) {
        if (str == null || reference == null) {
            return null;
        }

        try {
            return (T) ((reference.getType().equals(String.class)) ? str : objectMapper.readValue(str, reference));
        } catch (Exception e) {
            log.warn("parse String to Object exception,String:{},TypeReference<T>:{},errors:{}", str, reference.getType(), e);
            return null;
        }

    }
}
